package com.serli.sample.data.runner;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import org.apache.wicket.Request;
import org.apache.wicket.Response;
import org.apache.wicket.Session;
import org.apache.wicket.protocol.http.WebApplication;

import com.serli.sample.data.runner.domain.Trip;
import com.serli.sample.data.runner.service.TripService;
import com.serli.sample.data.runner.view.HomePage;

/**
 * Application object for your web application. If you want to run this
 * application without deploying, run the Start class.
 * 
 * @see wicket.myproject.Start#main(String[])
 */
public class WicketApplication extends WebApplication {
	private TripService service;
	private EntityManager manager;

	/**
	 * Constructor
	 */
	public WicketApplication() {
		manager = Persistence.createEntityManagerFactory(
				"datarunner-persistence").createEntityManager();
		service = new TripService(manager);
	}

	/**
	 * @see wicket.Application#getHomePage()
	 */
	public Class getHomePage() {
		return HomePage.class;
	}

	@Override
	public Session newSession(Request request, Response response) {
		return new WicketSession(request);
	}
	
	public List<Trip> getAllTrip() {
		return service.getAllOrderByName();
	}
	
	public Trip getTrip(String tripName) {
		return service.getByName(tripName);
	}

	public void removeTrip(String tripName) {
		if (tripName != null) {
			manager.getTransaction().begin();
			Trip trip = service.getByName(tripName);
			service.remove(trip);
			manager.getTransaction().commit();
		}
	}

	public void addTrip(Trip trip) {
		if (trip != null) {
			manager.getTransaction().begin();
			service.persist(trip);
			manager.getTransaction().commit();
		}
		
	}
}
